<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
// 应用公共文件
/**
 * @param int $code
 * @param string $msg
 * @param array $data
 * @return string
 * 返回接口数据格式
 * 李塔
 */
function api_return($code=200, $msg='', $data = array())
{
    if(!is_numeric($code)) {
        return '';
    }
    $result = array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    );
    echo json_encode($result,JSON_UNESCAPED_UNICODE);
    exit;
}
/**
 * @author Z
 * CreateTime 2020/9/24 11:46
 * get方式请求 获取网页文本
 */
function get_curl($url,$header = ['Accept:application/json','Content-Type:application/json;charset=utf-8'])
{
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    return json_decode($output,true);
}


/**
 * @param $url地址
 * @param $data参数
 * @return mixed
 * post提交
 * 李塔
 */
function http_post($url, $data=array(),$header = ['Accept:application/json','Content-Type:application/json;charset=utf-8'])
{
    $curl = curl_init();  //初始化
    curl_setopt($curl, CURLOPT_URL,$url);  //设置url
    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 设为0表示不检查证书 设为1表示检查证书中是否有CN(common name)字段 设为2表示在1的基础上校验当前的域名是否与CN匹配
    curl_setopt($curl, CURLOPT_USERAGENT, isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:''); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $returnData = curl_exec($curl);
    if($returnData === false){
        echo curl_error($curl);
        exit();
    }
    $returnData = json_decode($returnData,true);
    curl_close($curl);
    return $returnData;
}
/**
 * @author ASUS
 * @date 2020-11-26 12:46
 * flinPay支付
 */
function http_post_flin($url,$postData)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen(json_encode($postData))));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $res = curl_exec($ch);
    return json_decode($res,true);
}
/**
 * @param int $type
 * @return mixed
 * 获取客户端的ip
 * 李塔
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * @return array|false|string
 * @author ASUS
 * @date 2021-10-29 13:55
 * 获取服务器ip
 */
function get_server_ip()
{
    if(isset($_SERVER)){
        if($_SERVER["SERVER_ADDR"]){
            $ip = $_SERVER["SERVER_ADDR"];
        }else{
            $ip = $_SERVER["LOCAL_ADDR"];
        }
    }else{
        $ip = getenv("SERVER_ADDR");
    }
    return $ip;
}
/**
 * @param $content
 * 日志记录
 * 李塔
 */
function log_write($fileName,$content='',$parh="pcapi")
{
    $path = App::getRuntimePath() . 'logs' . DIRECTORY_SEPARATOR ."$parh/";
    if(!is_dir($path)){
        mkdir($path,0777,TRUE);
    }
    file_put_contents($path.$fileName.'_'.date("Ymd").'.log',$content.PHP_EOL,FILE_APPEND);
}

/**
 * @param string $time
 * @param string $format
 * @return array
 * @author ASUS
 * @date 2020-10-22 14:33
 * 获取指定日期前7天的所有日期
 */
function get_date($time="",$day=7, $format='Y-m-d')
{
    $time = $time != '' ? $time : time();
    //获取当前周几
    $date = [];
    for ($i=0; $i<$day; $i++){
        $date[$i] = date($format ,strtotime( '-' . $i .' days', $time));
    }
    return $date;
}
/**
 * @return mixed
 * 实例化redis对象
 * 李塔
 */
function redis($timeOut=0)
{
    $con = new \think\cache\driver\Redis();
    $con->connect(config('redis.host'), config('redis.port'), $timeOut);
    return $con;
}
/**
 * 生成唯一token
 * @return string
 * 李塔
 */
function token_create($namespace = null)
{
    static $guid = '';
    $uid = uniqid ( "", true );
    $data = $namespace;
    $data .= $_SERVER ['REQUEST_TIME'];     // 请求那一刻的时间戳
    $data .= $_SERVER ['HTTP_USER_AGENT'];  // 获取访问者在用什么操作系统
    $data .= $_SERVER ['SERVER_ADDR'];      // 服务器IP
    $data .= $_SERVER ['SERVER_PORT'];      // 端口号
    $data .= $_SERVER ['REMOTE_ADDR'];      // 远程IP
    $data .= $_SERVER ['REMOTE_PORT'];      // 端口信息
    $hash = strtoupper ( hash ( 'ripemd128', $uid . $guid . md5 ( $data ) ) );
    $guid =  substr ( $hash, 0, 8 ) . '-' . substr ( $hash, 8, 4 ) . '-' . substr ( $hash, 12, 4 ) . '-' . substr ( $hash, 16, 4 ) . '-' . substr ( $hash, 20, 12 );
    return $guid;
}
/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function array_sort($array, $keys, $sort = SORT_DESC)
{
    $keysValue = [];
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}

/**
 * @param $data
 * @param $pId
 * @return array
 * @author ASUS
 * @date 2020-09-09 15:29
 * 无限极分类
 */
function tree($data)
{
    $items = array();
    foreach ($data as $v) {
        $items[$v['id']] = $v;
    }
    $tree = array();
    foreach ($items as $k => $item) {
        if (isset($items[$item['parent_id']])) {
            $items[$item['parent_id']]['children'][] = &$items[$k];
        } else {
            $tree[] = &$items[$k];
        }
    }
    return $tree;
}

/**
 * 将参数拼接为url: key=value&key=value
 * @param $params
 * @return string
 */
function to_url_params( $params )
{
    $string = '';
    if( !empty($params) ){
        $array = array();
        foreach( $params as $key => $value ){
            $array[] = $key.'='.$value;
        }
        $string = implode("&",$array);
    }
    return $string;
}
/**
 * @return bool|string
 * @author ASUS
 * @date 2020-09-15 11:18
 * 获取7位的
 */
function create_unique($lenth=7)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = "";
    for ( $i = 0; $i < $lenth; $i++ )
    {
        $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $str ;
}
/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diff_two_days ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);
    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}
/**
 * @param $query
 * @return array
 * @author ASUS
 * @date 2020-11-30 15:04
 * 处理flinPay的回调结果
 */
function convert_url_query($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;
}

